<template>
    <div>
        <el-container style="height: 700px; border: 1px solid #eee">
            <!-- 顶部 el-header -->
            <el-header style="background-color: rgb(238, 241, 246)">
                <el-title style="font-size: 40px; display: flex; justify-content: center; align-items: center;">
                    TLIAS 智能学习辅助系统
                </el-title>
            </el-header>
            <el-container>
                <!-- 左侧列表 el-aside -->
                <el-aside class="el-menu" style="width: 180px; background-color: rgb(238, 241, 246);height: 100%">
                    <el-menu :default-openeds="['1', '3']" default-active="2" class="el-menu-vertical-demo"
                        style="min-height: 100%; overflow-x:hidden" background-color="rgb(48,65,86)" text-color="#fff"
                        active-text-color="#ffd04b" :collapse-transition="false" router :default-active="this.$route.path">
                        <div style="height: 40px; line-height: 40px; text-align: center">
                            <img src="../assets/logo.png" alt=""
                                style="width: 20px; height: 20px; position: relative; top: 5px; margin-right: 4px">
                            <b style="color: white">TLIAS 智能学习辅助系统</b>
                        </div>

                        <el-submenu index="1">
                            <template slot="title"><i class="el-icon-document"></i>
                                <span slot="title">教师管理</span>
                            </template>
                            <el-menu-item @click="getEmpList" :default-active="$route.path">查询教师信息</el-menu-item>
                        </el-submenu>

                        <el-submenu index="3">
                            <template slot="title"><i class="el-icon-document"></i>
                                <span slot="title">课程管理</span>
                            </template>
                            <el-menu-item @click="goToCourseInfo">查询课程信息</el-menu-item>
                        </el-submenu>
                    </el-menu>
                </el-aside>

                <el-main>
                    <!-- 条件查询表单 -->
                    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                        <el-form-item label="姓名">
                            <el-input v-model="searchForm.name" placeholder="姓名"></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">查询</el-button>
                        </el-form-item>

                        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                            @click="handleAddEmp">
                            添加
                        </el-button>
                    </el-form>



                    <!-- 表格 -->
                    <el-table :data="tableData" border>
                        <el-table-column prop="teacherId" label="编号" width="120"></el-table-column>
                        <el-table-column prop="teacherName" label="姓名" width="180"></el-table-column>
                        <el-table-column label="性别" width="140">
                            <template slot-scope="scope">
                                {{ scope.row.gender === 0 ? '男' : '女' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="age" label="年龄" width="140"></el-table-column>
                        <el-table-column prop="height" label="身高" width="140"></el-table-column>
                        <el-table-column prop="salary" label="工资" width="140">
                            <template slot-scope="scope">
                                {{ Number(scope.row.salary).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="nativePlace" label="籍贯" width="140"></el-table-column>
                        <el-table-column label="操作" width="330">
                            <template v-slot="{ row }">
                                <el-button type="primary" size="mini" @click="handleUpdate(row)">
                                    编辑
                                </el-button>
                                <el-button size="mini" type="danger" @click="handleDelete(row.teacherId)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 
                    :title="titleMap[dialogStatus] 通过它来判断显示是添加还是编辑
                    :visible.sync="dialogFormVisible" 控制弹窗是否显示，初始为flase
                    具体逻辑为：
                    1、当用户点击添加按钮时绑定了@click="handleAddEmp"方法，在此方法中把titleMap[dialogStatus]中的dialogStatus状态
                    改为this.dialogStatus = "create",此时窗口的title显示为添加

                    2、当用户点击编辑按钮时绑定了@click="handleUpdate"方法，在此方法中把titleMap[dialogStatus]中的dialogStatus状态
                    改为this.dialogStatus = "update",此时窗口的title显示为编辑

                    3、handleAddEmp和handleUpdate方法只是为了控制弹窗是显示添加还是编辑弹窗，并不是真正的添加和编辑方法向后端发送请求的

                     -->
                    <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
                        <!-- ref="dataForm" 校验参数 -->
                        <el-form :model="form" label-position="left" label-width="70px"
                            style="width: 400px; margin-left:50px;">
                            <el-form-item label="姓名" prop="teacherName">
                                <el-input v-model="form.teacherName" />
                            </el-form-item>

                            <el-form-item label="性别" prop="gender">
                                <el-radio-group v-model="form.gender">
                                    <el-radio :label="0">男</el-radio>
                                    <el-radio :label="1">女</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="年龄" prop="age">
                                <el-input v-model="form.age" />
                            </el-form-item>

                            <el-form-item label="身高" prop="height">
                                <el-input v-model="form.height" />
                            </el-form-item>

                            <el-form-item label="工资" prop="salary">
                                <el-input v-model="form.salary" />
                            </el-form-item>

                            <el-form-item label="籍贯" prop="nativePlace">
                                <el-input v-model="form.nativePlace" />
                            </el-form-item>

                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">
                                取消
                            </el-button>
                            <!-- 判断用户提交的是添加方法还是编辑方法 -->
                            <el-button type="primary" @click="dialogStatus === 'create' ? addData() : updateData()">
                                确定
                            </el-button>
                        </div>
                    </el-dialog>

                    <!-- 分页条 -->
                    <!-- 自定义分页
                     handleSizeChange改变展示数量的方法
                     handleCurrentChange  改变分页的方法
                    :current-page 当前页数
                     page-sizes 初始分页数量
                     total="total 总数量
     -->
                    <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                        :page-sizes="[5, 10, 20, 40]" :page-size="pageSize" :total="total"><!-- 后端返回的 -->
                    </el-pagination>

                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
//引入自定义的方法，用于调用后端接口
import { getList, addTeacher, deleteTeacher, updateTeacher } from '@/api/teacher'
export default {
    name: 'Teacher',
    data() {
        return {
            dialogStatus: " ",//添加或者编辑
            titleMap: {
                update: "编辑",
                create: "添加"
            },
            tableData: [],
            searchForm: {
                name: "",
                gender: ""
            },

            pageNum: 1,
            pageSize: 5,
            total: 0,//总条数
            currentPage: 1,//当前页
            dialogFormVisible: false,
            // 初始化或重置表单数据
            resetForm() {
                this.form = { 
                    teacherId: null,
                    teacherName: '',
                    salary: null,
                    gender: '',
                    age: null,
                    height: null,
                    nativePlace: ''
                };
            },
            form: {
                teacherName: '',
                gender: '',
                salary: '',
                age: '',
                height: '',
                salary: '',
                nativePlace: '',
            },
        }
    },
    methods: {
        goToCourseInfo() {
            this.$router.push('/Course');
        },
        onSubmit: function () {
            alert("查询数据");
        },
        //监控添加按钮是否触发
        handleAddEmp: function () {
            this.dialogStatus = "create"
            this.dialogFormVisible = true
            this.resetForm(); 
        },
        async addData() {
            // 先重置表单内容
           
            // 使用await关键字等待addTeacher方法的Promise对象完成
            await addTeacher(this.form)
                .then((response) => {
                    // 如果addTeacher成功，这里将关闭表单对话框（dialogFormVisible设为false）
                    this.dialogFormVisible = false;

                    // 打印服务端返回的消息
                    console.log(response.data.message);

                    // 根据服务器返回的结果，向用户显示成功的提示信息
                    if (response.data.code == 1) {
                        alert('教师信息添加成功');

                    } else {
                        alert('教师信息添加失败：' + response.data.msg); // 显示错误信息
                    }
                    this.getTeacherList()
                })
                .catch((error) => {
                    // 若请求过程中出现错误，则处理错误
                    console.error('添加教师信息时发生错误:', error);
                    alert('网络请求异常，请稍后再试');
                });
        },
        //监控编辑按钮是否触发
        handleUpdate: function (row) {
            this.form = row
            this.dialogStatus = "update"
            this.dialogFormVisible = true
        },
        async updateData() {
            await updateTeacher(this.form)
                .then((response) => {
                    this.dialogFormVisible = false
                    console.log(response.data.message)
                });

        },//监控删除按钮是否触发
        async handleDelete(teacherId) {
            await deleteTeacher(teacherId)
                .then((response) => {
                    if(response.data.code==1){
                        alert("删除成功")
                    }else{
                        alert("删除失败")
                    }
                })
                .catch((error) =>{
                    console.log(error)
                })
                this.getTeacherList()
        },
        async getTeacherList() {
            await getList(this.pageNum, this.pageSize)
                .then((response) => {
                    this.tableData = response.data.data.rows;
                    this.total = response.data.data.total
                });
        },
        handleSizeChange: function (val) {
            this.pageSize = val //每页展示数量
            this.getTeacherList()

        },
        handleCurrentChange: function (val) {
            this.pageNum = val //当前页码
            this.getTeacherList()
        }
    },
    /* 
    如果涉及操作DOM，不论是获取还是修改等等，都需要在mounted中执行。不然会由于无法获取到DOM而产生报错。
    如果不涉及DOM操作，可以在created中执行。此时的data数据和methods方法，整个vue实例已经生成。例如修改data，执行不涉及DOM的method。
    */
    mounted() {
        this.getTeacherList()
    },


}
</script>

<style></style>